﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using System.Text;

using Jarvis.Analytics;

namespace Jarvis.Utility
{
    class Preferences
    {
        private static Preferences _preferences;
        private Dictionary<string, object> _store;

        public static Preferences preferences
        {
            get
            {
                if (_preferences == null)
                    _preferences = new Preferences();

                return _preferences;
            }

            set
            {
                _preferences = value;
            }
        }

        public Preferences()
        {
            String appDataFolder = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\The Pennyworth Project\\Jarvis\\";
            String appData = appDataFolder + "Jarvis.preferences";

            if (File.Exists(appData))
            {
                IFormatter formatter = new BinaryFormatter();

                Stream s = new FileStream(appData, FileMode.Open, FileAccess.Read, FileShare.Read);
                _store = (Dictionary<string, object>)formatter.Deserialize(s);
                s.Close();
            }
            else
                _store = new Dictionary<string, object>();

            Console.WriteLine("Last Saved = " + this.Get("Last Saved"));

            this.Set("Last Launch", DateTime.Now);
        }

        private void Save()
        {
            _store["Last Saved"] = DateTime.Now;

            String appDataFolder = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\The Pennyworth Project\\Jarvis\\";
            String appData = appDataFolder + "Jarvis.preferences";

            if (!Directory.Exists(appDataFolder))
            {
                Directory.CreateDirectory(appDataFolder);

                this.Save();
            }
            else
            {
                IFormatter formatter = new BinaryFormatter();

                Stream s = new FileStream(appData, FileMode.Create, FileAccess.Write, FileShare.Read);
                formatter.Serialize(s, _store);

                s.Close();
            }
        }

        public object Get(String key)
        {
            try
            {
                return _store[key];
            }
            catch (KeyNotFoundException)
            {
                return null;
            }
        }

        public void Set(String key, object value)
        {
            Console.WriteLine("prefs => " + key + " = " + value);

            _store[key] = value;

            this.Save();

            AnalyticsManager.LogEvent("Preference changed", "'" + key + "' is now '" + value.ToString() + "'.");
        }
    }
}
